package com.xzc.java8.E_Parallel;

import org.junit.Test;

import java.util.function.Function;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/*
迭代型的流用并行不好，因为是将操作放在不同的线程里面
而最后是将这些线程一个个的调度，再将结果合并，相当于多线程串行，很慢。
 */
public class Iterator {
    public static long iterativeSum(long n) {
        long result = 0;
        for (long i = 1L; i <= n; i++) {
            result += i;
        }
        return result;
    }

    public static long parallelSum(long n) {
        return Stream.iterate(1L, i -> i + 1).limit(n).parallel().reduce(0L, Long::sum);
    }

    //没有装箱，拆箱，而且可以并行
    public static long rangedSum(long n) {
        return LongStream.rangeClosed(1, n).reduce(0L, Long::sum);
    }

    public static long measureSumPerf(Function<Long, Long> adder, long n) {
        long fastest = Long.MAX_VALUE;
        for (int i = 0; i < 1; i++) {
            long start = System.nanoTime();
            long sum = adder.apply(n);
            long duration = (System.nanoTime() - start) / 1000000;
            System.out.println("Result: " + sum);
            if (duration < fastest) fastest = duration;
        }
        return fastest;
    }

    public static void main(String[] args) {
        System.out.println("Iterative sum done in: " + measureSumPerf(Iterator::iterativeSum, 100000000) + " msecs");
//        System.out.println("Iterative sum done in: " + measureSumPerf(Iterator::parallelSum, 100000000) + " msecs");
        System.out.println("Iterative sum done in: " + measureSumPerf(Iterator::rangedSum, 100000000) + " msecs");
    }
}
